<template>
  <div class="search m_flex m_fdc">
    <!-- 搜索框 -->
    <div class="m_flex m_faic search_box">
      <i class="m_fs18 iconfont icon-fanhui back" @click="$router.back()"></i>
      <form class="m_flex m_faic m_f1 m_pr search_input" @submit.prevent="">
        <input ref="search" class="m_fs15 m_f1" type="search" v-model="kw" placeholder="输入关键词"
          @input="search(kw)" @keyup.enter="doSearch" @focus="showPost=false">
        <van-icon v-show="kw.length>0" name="clear" class="m_pa clear" @click="clear"/>
      </form>
      <span class="m_fs15 search_btn" @click="doSearch(kw)">搜索</span>
    </div>

    <div class="m_f1 search_content">
      <!-- 搜索历史 -->
      <div class="search_history" v-if="histories.length>0 && kw.length==0 && !showPost">
        <div class="m_flex m_faic m_fjcsb title">
          <div class="m_fs16 m_fw">历史搜索</div>
          <van-icon class="empty" name="delete-o" @click="emptyHistories"/>
        </div>
        <div class="history_list m_flex m_fwr m_fs15">
          <div class="history_item" v-for="item,i in histories" :key="i"
            @click="doSearch(item)">{{item}}</div>
        </div>
      </div>

      <!-- 搜索相关词条 -->
      <ul class="list" v-if="!showPost">
        <li class="m_flex m_fs16 item" v-for="item,i in kws" :key="i"
        @click="doSearch(item.replace(/<.*?>/ig,''))">
          <i class="iconfont icon-sousuo"></i>
          <div v-html="item"></div>
        </li>
      </ul>

      <!-- 搜索结果 -->
      <div class="post_list" v-else>
        <div class="post_item" v-for="item,index in searches" :key="item.id" @click="toPlayList(searches, index)">
          <van-image class="post" fit="cover" :src="ip+item.coverUrl"/>
          <div class="info m_flex">
            <van-image v-if="item.avatarUrl" class="avatar m_br50p" fit="cover" :src="ip+item.avatarUrl"/>
            <div v-else class="m_br50p m_tac m_fs16 m_fw avatar">{{item.username.slice(0,1)}}</div>
            <div class="nickname m_f1 van-ellipsis">{{item.nickname?item.nickname:item.username}}</div>
            <div class="likeCount">
              <van-icon name="like-o" /> {{item.likeCount}}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {mapState, mapMutations} from 'vuex'
export default {
  data(){
    return{
      kw: '',
      kws: [],
      histories: [],
      searches: [],
      timer: null,
      showPost: false
    }
  },
  computed: {
    ...mapState(['ip'])
  },
  watch: {
    kw(){
      if(this.kw.length==0){
        this.searches = []
        this.kws = []
        this.showPost = false
      }
    }
  },
  methods:{
    // 辅助
    ...mapMutations('m_video',['setVideoList']),
    // 清空关键字
    clear(){
      this.kw = ''
    },
    // 清空历史搜索
    emptyHistories(){
      this.$refs.search.focus()
      this.histories = []
      localStorage.setItem('histories','[]')
    },
    // 搜索：相关词条
    search(kw){
      if(kw.trim().length==0) return
      this.timer = setTimeout(()=>{
        this.getSearch(kw)
        clearTimeout(this.timer)
        this.timer = null 
      },300)
    },
    // 搜索：相关视频
    doSearch(kw){
      this.kw = kw
      this.showPost = true
      this.histories.push(kw)
      this.histories = [...new Set(this.histories)]
      localStorage.setItem('histories',JSON.stringify(this.histories))
      this.getSearch(kw)
    },
    // 获取搜索结果
    getSearch(kw){
      this.axios.get(`api/search/${kw}`).then(res=>{
        if(res.code==0){
          this.searches = res.dt
          this.kws = res.dt.map(item => {
            item.title = item.title.replaceAll(kw,'<span class="highlight">'+kw+'</span>')
            return item.title
          });
          this.kws = [...new Set(this.kws)]
        }else{
          this.$toast('搜索失败')
        }
      })
    },
    // 去播放列表页
    toPlayList(list, initIndex){
      this.setVideoList(list)
      this.$router.push({path:'/play',query:{initIndex}})
    },
  },
  created(){
    this.histories = JSON.parse(localStorage.getItem('histories') || '[]')
  }
}
</script>

<style lang="scss">
.search{
  height: 100vh;
}
// 搜索框
.search_box{
  gap: 10px;
  padding: 0 12px;
  height: 50px;
  .search_input{
    width: 0;
    background: #eeeef6;
    height: 38px;
    border-radius: 4px;
    gap: 5px;
    padding: 0 5px;
    input{
      width: 0;
      padding: 0 7px;
      background: transparent;
      &::-webkit-search-cancel-button{ -webkit-appearance: none;}
    }
    .clear{
      color: #c7c8cc;
      right: 12px;
    }
  }
}
// 
.search_content{
  height: calc(100vh - 51px);
  overflow: scroll;
  &::-webkit-scrollbar{ display: none;}
}
// 搜索历史
.search_history{
  .title{
    padding: 0 20px;
    height: 40px;
    color: #282828;
    .empty{ color: #9a9a9a;}
  }
  .history_list{
    gap: 10px;
    padding: 4px 20px;
    .history_item{
      background: #f8f8f8;
      color: #1a1a1a;
      line-height: 30px;
      padding: 0 15px;
      border-radius: 15px;
    }
  }
}
// 搜索相关词条
.list{
  padding: 5px 15px;
  .item{
    gap: 15px;
    line-height: 50px;
    i{ color: #999;}
    .highlight{ color: #008080;}
  }
}
// 
.post_list{
  column-count: 2;
  column-gap: 2px;
  .post_item{
    break-inside: avoid;
    .info{
      padding: 0 5px;
      gap: 8px;
      color: #575757;
      font-size: 12px;
      .avatar{
        height: 30px;
        width: 30px;
        background: #008080;
        line-height: 30px;
        color: #fff;
        transform: translateY(-50%);
      }
      .nickname{ color: #575757; }
      .likeCount{ color: #1b1b1b; }
    }
  }
}
</style>